﻿using RohdeSchwarz.RsPwrMeter;
using System;
using Shared.Method;

namespace TestSystem
{
    public class Testing
    {
        //private static string s_switchLocalIp, s_switchIp;
        private static int /*s_switchLocalPort, s_switchPort, s_countTimes, */s_testTimes;
        private static double s_passValueLeft, s_passValueRight;

        private static RsPwrMeter s_driver = null;

        private static YcdTelnetSecond s_telsecond = null;
        private static readonly object LockObj = new object();

        //静态类，用于功率计测试光猫
        public static void InitTesting(
            string switchlocalIp, int switchlocalport,
            string switchIp, int switchport,
            double passvalueleft, double passvalueright,
            int countTimes, int testTimes)
        {
            //s_switchLocalIp = switchlocalIp;
            //s_switchLocalPort = switchlocalport;
            //s_switchIp = switchIp;
            //s_switchPort = switchport;

            s_passValueLeft = passvalueleft;
            s_passValueRight = passvalueright;

            //s_countTimes = countTimes;
            s_testTimes = testTimes;

            //初始化连接耦合板开关
            Random ra = new Random();
            int localportSwitch = ra.Next(switchlocalport, switchlocalport + 200);

            //连接开关
            s_telsecond = new YcdTelnetSecond(switchIp, switchlocalIp, localportSwitch, switchport);
            if (s_telsecond.Connect() == false || s_telsecond.Connected == false)
            {
                throw new Exception("连接耦合板开关失败");
            }

            //初始化类
            try
            {
                //AppendRichTextBox("Driver session initializing...");
                s_driver = new RsPwrMeter("USB::0x0aad::0x00e2::104701", true, true, "Simulate=False");
                //AppendRichTextBox("Successfull");
            }
            //in case of the initializing error the driver throws an Ivi.Driver.IOException
            catch (Ivi.Driver.IOException e)
            {
                throw new Exception(e.ToString());
                //return false;
            }

            try
            {
                //setting the OPC timeout in ms (not the VISA timeout!!!)
                //driver.UtilityFunctions.OPCTimeout = 600;

                s_driver.Measurement.Channel["CH1"].Continuous = false;
                s_driver.Channel["CH1"].Frequency = 2.4e9;
                s_driver.Channel["CH1"].Mode = MeasurementMode.BurstAv;
                s_driver.Channel["CH1"].Averaging.Enabled = true;
                s_driver.Channel["CH1"].Trigger.Source = TriggerSource.Bus;
                s_driver.Channel["CH1"].Averaging.Count = countTimes;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }

        public static void Stop()
        {
            s_driver?.Close();
        }

        public static bool ThruPutTesting(string portStr, bool left, double offset, out double resultNumber)
        {
            bool testRet = false;

            resultNumber = 0;

            lock (LockObj)//时分复用功率计
                if (TelnetSendAndRecv(s_telsecond, string.Format("drvRSWSetSwitchState {0}", portStr), "Success") == true)//切换耦合板成功
                {
                    System.Threading.Thread.Sleep(1000);//等待1秒切换

                    for (int i = 0; i < s_testTimes; i++)
                    {
                        s_driver.Measurement.Channel["CH1"].Initiate();
                        s_driver.Measurement.SendSoftwareTrigger();

                        double[] result = s_driver.Measurement.Fetch();

                        resultNumber = Watt2dBm(result[0]);//返回测试结果

                        if (
                            (left && (Watt2dBm(result[0]) + offset) >= s_passValueLeft)
                            || (!left && (Watt2dBm(result[0]) + offset) >= s_passValueRight)
                            )
                        {
                            testRet = true;
                        }
                        else
                        {
                            testRet = false;
                        }

                        if (testRet == false)
                        {
                            System.Threading.Thread.Sleep(1000);
                            continue;
                        }
                        else
                        {
                            break;
                        }
                    }

                    if (testRet == false) return false;
                    else return true;
                }
                else
                {
                    return false;
                }
        }

        /// <summary>
        /// 从double转换为dBm
        /// </summary>
        /// <param name="dWatt"></param>
        /// <returns></returns>
        private static double Watt2dBm(double dWatt)
        {
            return (dWatt < 1.0e-19) ? -160.0 : (10.0 * (Math.Log10(dWatt) + 3.0));
        }

        /// <summary>
        /// TELNET命令
        /// </summary>
        /// <param name="tel"></param>
        /// <param name="cmdStr"></param>
        /// <param name="keyWord"></param>
        /// <returns></returns>
        private static bool TelnetSendAndRecv(YcdTelnetSecond tel, string cmdStr, string keyWord)
        {
            if (tel == null || tel.Connected == false || string.IsNullOrEmpty(cmdStr) || string.IsNullOrEmpty(keyWord)) return false;

            //发送telnet指令_语音测试

            //tel.Send(cmdStr);

            string msg;

            //bool ret = tel.GetReturnMsg(keyWord, out msg);
            bool ret = tel.SendAndRecv(cmdStr, keyWord, out msg);

            return ret;
        }
    }
}
